<?php

namespace App\Http\Controllers;

use App\Http\Requests\ChangePasswordRequest;
use App\Http\Requests\UpdateProfileRequest;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class ProfileController extends Controller
{
    protected $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
        $this->middleware('auth.api');
    }

    /**
     * 获取当前用户信息
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function show()
    {
        $user = auth()->user();
        $user->load(['roles', 'department']);
        
        // 获取权限服务
        $permissionService = app(\App\Services\PermissionService::class);
        
        // 检查是否是admin角色
        $isAdmin = $user->isAdmin();
        
        // 获取按钮权限（按资源分组）
        $buttonPermissions = $permissionService->getUserButtonPermissions($user);
        
        // 获取角色代码列表
        $roleCodes = $user->roles->pluck('code')->toArray();
        
        return $this->success([
            'id' => $user->id,
            'username' => $user->username,
            'nickname' => $user->nickname,
            'email' => $user->email,
            'phone' => $user->phone,
            'avatar' => $user->avatar,
            'status' => $user->status,
            'roles' => $user->roles->pluck('name'),
            'role_codes' => $roleCodes,
            'is_admin' => $isAdmin,
            'permissions' => $buttonPermissions,
            'department' => $user->department ? $user->department->name : null,
            'created_at' => $user->created_at ? $user->created_at->setTimezone(config('app.timezone', 'Asia/Shanghai'))->format('Y-m-d H:i:s') : null,
        ], '获取成功');
    }

    /**
     * 更新个人资料
     *
     * @param UpdateProfileRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(UpdateProfileRequest $request)
    {
        $user = auth()->user();
        
        $user->update($request->validated());
        $user->refresh();
        $user->load(['roles', 'department']);

        return $this->success([
            'id' => $user->id,
            'username' => $user->username,
            'nickname' => $user->nickname,
            'email' => $user->email,
            'phone' => $user->phone,
            'avatar' => $user->avatar,
        ], '更新成功');
    }

    /**
     * 修改密码
     *
     * @param ChangePasswordRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePassword(ChangePasswordRequest $request)
    {
        try {
            $user = auth()->user();
            
            // 更新密码
            $user->update([
                'password' => Hash::make($request->password),
            ]);

            // 记录操作日志
            try {
                \App\Models\OperationLog::create([
                    'user_id' => $user->id,
                    'username' => $user->username,
                    'method' => 'POST',
                    'path' => '/api/profile/password',
                    'params' => [],
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                    'status' => 'success',
                ]);
            } catch (\Exception $e) {
                // 记录日志失败不影响密码修改
                \Log::warning('记录密码修改操作日志失败: ' . $e->getMessage());
            }

            return $this->success(null, '密码修改成功');
        } catch (\Exception $e) {
            \Log::error('修改密码失败: ' . $e->getMessage(), [
                'user_id' => auth()->id(),
                'exception' => $e,
            ]);
            
            return $this->error('密码修改失败，请稍后重试', 500);
        }
    }

    /**
     * 上传头像
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadAvatar(Request $request)
    {
        $request->validate([
            'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        try {
            $file = $request->file('avatar');
            $extension = $file->getClientOriginalExtension();
            $filename = uniqid() . '.' . $extension;
            $path = $file->storeAs('avatars/' . date('Y/m/d'), $filename, 'public');
            
            $user = auth()->user();
            
            // 删除旧头像
            if ($user->avatar && \Storage::disk('public')->exists(str_replace('/storage/', '', $user->avatar))) {
                \Storage::disk('public')->delete(str_replace('/storage/', '', $user->avatar));
            }
            
            $user->update([
                'avatar' => '/storage/' . $path,
            ]);

            return $this->success([
                'avatar' => '/storage/' . $path,
            ], '上传成功');
        } catch (\Exception $e) {
            return $this->error('上传失败：' . $e->getMessage(), 500);
        }
    }
}

